import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
// 根据环境不同引入不同api地址
import { baseApi } from '@/config'
// create an axios instance
// 生产环境，测试和正式
const IS_PROD =true || ['production', 'prod'].includes(process.env.NODE_ENV)
const service = axios.create({
  baseURL: IS_PROD?'https://zg.7ioe.cn/api':'https://zg.7ioe.cn/test/api', // url = base api url + request url
  // baseURL: 'https://zg.7ioe.cn/test/api', // url = base api url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        loadingType: 'spinner',
        forbidClick: true
      })
    }
    // if (store.getters.token) {
    //   config.headers['wx-token'] = sessionStorage.getItem('token')
    // }
    // config.headers['wx-token'] = sessionStorage.getItem('token')
     config.headers['wx-token'] = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJvUHVsVTVzcVhjSjBiWkZWdXQ3ZG9fUzRBdTJVIn0.RRAZCBbRl9QWU86673jw7Ggklpw8LNxUW0vwpHU8PCw'
    // config.headers['wx-token'] ='eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJvUHVsVTVqQTg2WUw3V0twbXhMOFYzWll2ZVlrIn0.mhMvOtAaRAcuyyRo13Wuiug63nYmujC0rPN5oIoZkZk'
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    const res = response.data
    if (res.code && res.code !== 200) {
      // 登录超时,重新登录
      if (res.code === 406) {
        location.href = '/wexin'
        // store.dispatch('FedLogOut').then(() => {
        //   location.reload()
        // })
      }
      return Promise.reject(res || 'error')
    } else {
      return Promise.resolve(res)
    }
  },
  error => {
    Toast.clear()
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
